package com.nuaa.service.impl;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.nuaa.dao.inter.CustomDaoInter;
import com.nuaa.domain.user.customer.CustomerInfo;
import com.nuaa.service.inter.CustomServiceInter;
import com.nuaa.utils.AjaxMsg;
import com.nuaa.utils.CustomCodeUtil;
import com.nuaa.utils.EcodeByMD5;

@Service("customService")
public class CustomServiceImpl implements CustomServiceInter{

	@Resource
	private CustomDaoInter customDao;
	
	@Override
	@Transactional
	public AjaxMsg add(CustomerInfo custom){
		AjaxMsg msg = new AjaxMsg();
		List<String> loginNameList = customDao.getAllLoginName();
		for(String loginName:loginNameList){
			if(custom.getLogin_name().equals(loginName)){
				msg.setSuccess(false);
				msg.setMsg("用户名已经使用！请重新指定");
				return msg;
			}
		}
		String customerNo = CustomCodeUtil.getCustomNo(customDao.getMaxId(custom.getClass()));
		custom.setCustomerNo(customerNo);
		custom.setLogin_password(EcodeByMD5.ecodeByMD5(custom.getLogin_password()));
		try{
			customDao.add(custom);
			msg.setSuccess(true);
			msg.setMsg("注册成功！");
		}catch(Exception e){
			msg.setSuccess(false);
			msg.setMsg(e.toString());
		}
		return msg;
	}

	@Override
	@Transactional
	public void updateInfo(CustomerInfo custom) throws Exception {
		List<CustomerInfo> cutomList = customDao.getAll();
		for(CustomerInfo tempCustom:cutomList){
			if(custom.getId()!=tempCustom.getId()&&custom.getLogin_name().equals(tempCustom.getLogin_name()))
				throw new Exception("用户名已经使用！");
		}
		try{
			customDao.update(custom);
		}catch(Exception e){
			e.printStackTrace();
			throw new Exception("更新发生异常！");
		}
	}
	
	@Override
	@Transactional
	public void delete(Integer[] ids) throws Exception{
		try{
			customDao.delete(ids);
		}catch(Exception e){
			e.printStackTrace();
			throw new Exception("删除发生异常");
		}
	}
	
	public List<Map<String,Object>> getAllCustomerNos(){
		String sql = "select id,customerNo as text from customer_info";
		List<Map<String,Object>> list = customDao.searchForMap(sql);
		return list;
	}

	@Override
	public CustomerInfo getById(Integer id) {
		return customDao.find(CustomerInfo.class, id);
		
	}
	@Transactional
	@Override
	public AjaxMsg resetPass(String ids) {
		AjaxMsg msg = new AjaxMsg();
		String [] idArray = ids.split(",");
		try{
			for (String id : idArray) {
				String sql = "update customer_info set login_password = 'ICy5YqxZB1uWSwcVLSNLcA==' where id ='"+id+"'";
				customDao.update(sql);
			}
			msg.setSuccess(true);
			msg.setMsg("重置成功！密码重置为123");
		}catch (Exception e) {
			msg.setSuccess(false);
			msg.setMsg("重置失败！");
		}
		return msg;
	}
}
